class Communication {
    constructor(evnet, url) {
        this.event = evnet;
        this.url = url || "ws://localhost:8888/ws";
        this.events = {};
        this.headFun = null;
        this.timer = null;
        this._initInterval(); //加载定时心跳
    }

    _initInterval() {
        let self = this;
        this.timer = setInterval(() => {
            self._trigger({type: 'timer', data: '定时器'});
            if (this.headFun) {
                this.headFun(self);
            }
        }, 1000 * 5);
    }

    setHead(fun) {
        this.headFun = fun;
        return this;
    }

    init() {
        let self = this;
        if (window.WebSocket) {
            console.info("开始连接ws地址", this.url);
            this.socket = new window.WebSocket(this.url);
            this.socket.onmessage = function (ev) {
                self._trigger(ev.data);
            }
            this.socket.onopen = function (ev) {
                self._trigger({type: 'open', data: '连接成功'});
            }
            this.socket.onclose = function (ev) {
                self._trigger({type: 'close', data: '连接关闭,三秒后重连'});
                self._reopen();
            }
            this.socket.onerror = function (ev) {
                self._trigger({type: 'error', data: ev});
            }
        } else {
            self._trigger({type: 'not_support', data: '不支持webSocket协议'});
            throw "当前浏览器不支持webSocket协议进行通信";
        }
        return this;
    }

    _reopen() {
        let self = this;
        setTimeout(() => {
            self.init();
        }, 3000)
    }

    _trigger(data) {
        let json = (typeof data) == 'string' ? JSON.parse(data) : data;
        this.event.trigger(json.type, json);
    }

    login(self, token, fromUser) {
        token = token || self.$store.state.userInfo.token;
        fromUser = fromUser || self.$store.state.userInfo.userId
        let data = {type: 'Login', no: new Date().getTime(), data: token, from: fromUser, to: ''};
        this.send(JSON.stringify(data));
    }

    sendTo(self, from, to, msg, type) {
        msg = (typeof msg == 'string') ? msg : JSON.stringify(msg);
        let data = {type: type, no: new Date().getTime(), data: msg, from: from, to: to};
        this.send(JSON.stringify(data));
        return data;
    }

    send(msg) {
        if (!window.WebSocket) {
            return;
        }
        if (this.socket.readyState == WebSocket.OPEN) {
            this.socket.send(msg);
        } else {
            throw "连接断开了";
        }
        return this;
    }

    close() {
        clearInterval(this.timer);
        if (this.socket.readyState == WebSocket.OPEN) {
            this.socket.close();
        }
    }

}

export default Communication;
